package org.zyj.io.example.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

public class EchoClient {

    static final String HOST = "127.0.0.1";
    static final int PORT = 11222;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)//不需要等待组装成大TCP包
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) { //每次建立连接的时候都会被调用
                            ch.pipeline()
                                    .addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture f = b.connect(HOST, PORT).sync();
            f.channel().closeFuture().sync();//阻塞主线程, 程序不会退出
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class EchoClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            //建立连接之后, 立刻发送一条消息
            String sendMsg = "这是一条消息!";
            System.out.println(sendMsg);
            ByteBuf byteBuf = Unpooled.copiedBuffer(sendMsg, StandardCharsets.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            //读取服务端返回的信息
            ByteBuf buf = (ByteBuf) msg;
            if (buf.isReadable()) {
                System.out.println(buf.toString(StandardCharsets.UTF_8));
            }
        }
    }
}
